package com.kamfu.function.common;

import com.kamfu.makingjavafunctional.Result02;

/**
 * 表示条件
 *
 * @param <T>
 */
public class Case<T> extends Tuple<Supplier<Boolean>, Supplier<Result02<T>>> {

    /**
     * @param booleanSupplier 表示条件
     * @param resultSupplier  表示结果
     */
    private Case(Supplier<Boolean> booleanSupplier, Supplier<Result02<T>> resultSupplier) {
        super(booleanSupplier, resultSupplier);
    }

    public static <T> Case<T> mcase(Supplier<Boolean> condition, Supplier<Result02<T>> value) {
        return new Case<>(condition, value);
    }

    public static <T> DefaultCase<T> mcase(Supplier<Result02<T>> value) {
        return new DefaultCase<>(() -> true, value);
    }

    private static class DefaultCase<T> extends Case<T> {

        private DefaultCase(Supplier<Boolean> booleanSupplier, Supplier<Result02<T>> resultSupplier) {
            super(booleanSupplier, resultSupplier);
        }
    }

    /**
     * 匹配条件
     *
     * @param defaultCase
     * @param matchers
     * @param <T>
     * @return
     */
    @SafeVarargs
    public static <T> Result02<T> match(DefaultCase<T> defaultCase, Case<T>... matchers) {
        for (Case<T> aCase : matchers) {
            if (aCase._1.get()) {
                return aCase._2.get();
            }
        }
        return defaultCase._2.get();
    }
}
